﻿using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using EPiServer;
using EPiServer.Configuration;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAccess;
using EPiServer.Security;
using EPiServer.UI.WebControls;
using EPiServer.Web.WebControls;

namespace ElencySolutions.MultipleProperty.Edit
{
    using System;
    using EPiServer.UI;

    public class MultiplePropertyCopyProperty : SystemPageBase
    {

        #region Members

        private PageData _page;
        protected Literal PageNameLiteral;
        protected Literal PropertyNameLiteral;
        protected Panel panMessage;
        protected Literal litMessage;
        protected PlaceHolder FormPlaceHolder;
        protected InputPageReference CopyToPageLinkUrl;
        protected PlaceHolder PropertiesPlaceHolder;
        protected DropDownList PropertyToReplaceDropDownList;
        protected ToolButton CopyButton;

        #endregion Members

        #region Properties

        public int PageId
        {
            get
            {
                return int.Parse(Request.QueryString["PageId"]);
            }
        }

        public int WorkId
        {
            get
            {
                return int.Parse(Request.QueryString["WorkId"]);
            }
        }

        public string Language
        {
            get
            {
                return Request.QueryString["language"].Trim();
            }
        }

        public string PropertyName
        {
            get
            {
                return Request.QueryString["PropertyName"].Trim();
            }
        }

        #endregion Properties


        protected void CopyButtonClick(object sender, EventArgs e)
        {
            Copy();
        }

        protected void PageChangedButtonClick(object sender, EventArgs e)
        {
            PageChanged();
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            Page.MasterPageFile = Settings.Instance.UIUrl + "MasterPages/EPiServerUI.Master";
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            PageLoadController();
        }

        private void PageLoadController()
        {
            DataBind();

            _page = DataFactory.Instance.GetPage(new PageReference(PageId, WorkId), new LanguageSelector(Language));

            PageNameLiteral.Text = _page.PageName;
            PropertyNameLiteral.Text = PropertyName;
            CopyButton.Enabled = false;
        }

        private void PageChanged()
        {
            PropertyToReplaceDropDownList.Items.Clear();
            string value = CopyToPageLinkUrl.ValueControl.Value;

            if (string.IsNullOrEmpty(value))
            {
                PropertiesPlaceHolder.Visible = false;
                return;
            }

            PageData page = GetLatestSelectedPageVersion(value);

            if (!_page.QueryDistinctAccess(AccessLevel.Edit))
            {
                SetError(Translate("writeAccess"));
                PropertiesPlaceHolder.Visible = false;
                return;
            }

            // if no suitable properties maybe show a message
            Type typeToMatch = _page.Property[PropertyName].GetType();
            IEnumerable<PropertyData> propreties = page.Property.Where(current => current.GetType().Equals(typeToMatch) && !current.IsDynamicProperty && current.IsPropertyData && !current.IsMetaData);
            
            foreach (PropertyData property in propreties)
                PropertyToReplaceDropDownList.Items.Add(new ListItem(property.TranslateDisplayName(), property.Name));

            CopyButton.Enabled = (PropertyToReplaceDropDownList.Items.Count > 0);

            if (!CopyButton.Enabled)
            {
                PropertiesPlaceHolder.Visible = false;
                SetError(Translate("pageSelectedHasNoMatchingProperties"));
            }
            else
                PropertiesPlaceHolder.Visible = true;
            
        }

        private PageData GetLatestSelectedPageVersion(string id)
        {
            PageData page = DataFactory.Instance.GetPage(new PageReference(int.Parse(id), true));
            PageVersionCollection pageVersions = PageVersion.List(page.PageLink);
            return DataFactory.Instance.GetPage(pageVersions.Last().ID);
        }

        private void SetError(string errorText)
        {
            litMessage.Text = errorText;
            panMessage.Visible = true;
        }

        protected new string Translate(string key)
        {
            return LanguageHelper.Translate(string.Format("/elencySolutionsMultipleProperty/{0}", key));
        }

        private void Copy()
        {
            if (!IsValid)
                return;

            PropertyData propertyData = _page.Property[PropertyName];
            string propertyNameToCopyTo = PropertyToReplaceDropDownList.SelectedItem.Value;
            PageData pageToCopyTo = GetLatestSelectedPageVersion(CopyToPageLinkUrl.PageLink.ID.ToString()).CreateWritableClone();

            PropertyData propertyToCopyTo = pageToCopyTo.Property[propertyNameToCopyTo];
            propertyToCopyTo.Value = propertyData.Value;

            try
            {
                propertyToCopyTo.ParseToSelf(propertyData.Value.ToString());
            }
            catch
            {
                propertyToCopyTo.Value = propertyData.Value;
            }

            try
            {
                PageReference pageReference = DataFactory.Instance.Save(pageToCopyTo, SaveAction.Save | SaveAction.ForceNewVersion);

                string url = ResolveUrl(Settings.Instance.UIUrl.ToString());

                if (!url.EndsWith("/"))
                    url += "/";

                url += string.Format("edit/EditPanel.aspx?id={0}_{1}", pageReference.ID, pageReference.WorkID);
                SetError(string.Format(Translate("propertyCopyingSuccessful"), url));
            }
            catch
            {
                SetError(Translate("propertyCopyingUnsuccessful"));
            }
        }

    }
}
